import {
  Component,
  ChangeDetectionStrategy,
  OnInit,
  ChangeDetectorRef,
  Input,
  OnDestroy,
  Output,
  EventEmitter,
} from '@angular/core';
import { _HttpClient } from '@delon/theme';
import { of, zip, Observable, fromEvent, Subject } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { NzMessageService } from 'ng-zorro-antd';

@Component({
  selector: 'product-cell',
  templateUrl: './product-cell.component.html',
  styleUrls: ['./product-cell.component.less'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ProductCellComponent implements OnInit, OnDestroy {
  @Input()
  p = null;
  // true-单个sku  false-根据style合并sku
  @Input()
  mode = true;
  @Output()
  goDetail = new EventEmitter<any>();
  @Output()
  showGallery = new EventEmitter<any>();

  loading = false;
  products = [];
  urls = [];
  // 切换的索引
  index = 0;

  constructor(private cdr: ChangeDetectorRef, private http: _HttpClient, public msg: NzMessageService) {}

  ngOnInit() {
    const { mode, p } = this;
    this.products = mode ? [p] : [...p.prods];
    // tslint:disable-next-line: no-shadowed-variable
    for (const p of this.products) {
      if (p.pic) {
        p.url = `${window.location.origin + window.location.pathname}/cf/admin/sysfile/f/${p.pic}`;
      }
    }
  }

  ngOnDestroy() {
    this.cdr.detach();
  }

  visibleChange(idx, e) {
    const { products } = this;
    if (e && !products[idx].productDTO) {
      const queryKey1 = products[idx].productCd;
      const queryKey2 = products[idx].sap;
      const api = [
        this.http.get(`/cf/prod/sys-prod/view/${queryKey1}`),
        this.http.get(`/cf/prod/sys-prod/stock?sap=${queryKey2}`),
      ];
      this.loading = true;
      zip(...api)
        .pipe(
          catchError(([prodinfo, stock]) => {
            return [prodinfo, stock];
          }),
        )
        .subscribe(([prodinfo, stock]) => {
          this.loading = false;
          if (stock.status === 200) {
            products[idx].stockDTO = stock.data;
          }
          if (prodinfo.status === 200) {
            products[idx].productDTO = prodinfo.data.product;
            products[idx].extraDTO = prodinfo.data.extra;
            products[idx].priceDTO = prodinfo.data.price;
          }
          this.cdr.detectChanges();
        });
      this.cdr.detectChanges();
    }
  }

  emitDetail() {
    this.goDetail.emit(this.index);
  }
  emitGallery() {
    this.showGallery.emit(this.index);
  }

  pre() {
    if (this.index >= 1) {
      this.index--;
    }
  }
  next() {
    if (this.index < this.products.length - 1) {
      this.index++;
    }
  }
}
